<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>项目选择</title>
    <!-- 引入其它组件 -->
    <!-- 引入 layui -->
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/app.css">
    <style>
        .layui-form-label {
            width: 100px;
        }

        .layui-input-block {
            margin-left: 130px;
        }

        .layui-table-cell {
            white-space: nowrap;
        }

        /* .tip-cell {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            display: block;
            cursor: default;
            max-width: 100%;
        } */

        .layui-table td[data-field="design_code"],
        .layui-table td[data-field="project_name"] {
            text-align: left !important;
        }

        .layui-table td[data-field="money_labor"],
        .layui-table td[data-field="money_material"],
        .layui-table td[data-field="total"] {
            text-align: right !important;
        }
    </style>
</head>

<body>
    <div class="layui-fluid layer-font">
        <div class="layui-card">
            <div class="layui-card-body">
                <!-- 固定搜索栏 -->
                <div class="layui-form" style="flex-shrink: 0; padding-bottom: 10px;">
                    <div class="layui-row" style="width:720px; display: flex; align-items: center;">
                        <div style="flex:1; margin-right: 10px;">
                            <input type="text" name="search" id="search-input" placeholder="输入工程编码/名称"
                                class="layui-input" lay-verify="search">
                        </div>
                        <div style="width:100px;">
                            <button class="layui-btn layui-btn-sm" id="btn-search" type="button">搜索</button>
                        </div>
                    </div>
                </div>
                <!-- 数据表格 -->
                <table id="projectTable" lay-filter="projectTable"></table>
            </div>
        </div>
    </div>
    <!-- <script type="text/html" id="ID-table-switch">
        <input type="checkbox" name="status" value="{{= d.filed }}" lay-filter="demo-templet-status" {{=d.filed ? "checked"
        : "" }}>
    </script> -->
    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/layui/layui.js"></script>
    <script type="text/html" id="ID-table-switch">
        <input type="checkbox" name="status" value="{{= d.filed }}" 
           lay-filter="demo-templet-status" 
           {{= d.filed ? "checked" : "" }} 
           style="pointer-events: none;" 
           lay-ignore>
    </script>

    <script>
        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;
            var designType = getUrlParam('design_type');
            var tableData = []; // 存储所有数据
            var isComposing = false; // 输入法状态

            // 初始化表格结构
            function initTable() {
                table.render({
                    elem: '#projectTable',
                    page:true,
                    page: {
                        layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'], // 完整的布局
                        prev: '上一页',
                        next: '下一页',
                        groups: 5, // 连续显示页码数
                        first: '首页',
                        last: '尾页'
                    },
                    limits: [10, 20, 50, 100],
                    limit: 10,
                    fixed: true, // 固定表头
                    maxHeight: 'full-100',
                    cols: [[
                        { type: 'numbers', title: '序号', width: 60 },
                        { field: 'design_code', title: '设计编码', width: 160 },
                        { field: 'project_name', title: '项目名称', width: 440 },
                        {
                            field: 'money_labor', title: '人工费', width: 100, templet: function (d) {
                                return d.money_labor ? d.money_labor.toFixed(2) : '0.00';
                            }
                        },
                        {
                            field: 'money_material', title: '材料费', width: 100, templet: function (d) {
                                return d.money_material ? d.money_material.toFixed(2) : '0.00';
                            }
                        },
                        {
                            field: 'total', title: '合计', width: 100, templet: function (d) {
                                var labor = d.money_labor || 0;
                                var material = d.money_material || 0;
                                return (labor + material).toFixed(2);
                            }
                        },
                        { field: 'filed', title: '存档', width: 60, align: 'center', templet: '#ID-table-switch' },
                    ]],
                    data: [] // 初始为空数据
                });
            }

            // 加载数据函数
            function loadData() {
                // 显示加载中
                var loadingIndex = layer.load(1);

                http.get(API_CONFIG.ENDPOINTS.PROJECT_LIST, {
                    design_type: Number(designType)
                }).then(function (res) {
                    layer.close(loadingIndex);

                    if (res.code === 0) {
                        tableData = res.data || [];
                        // 重新渲染表格数据
                        table.reload('projectTable', {
                            data: tableData,
                            page: true
                        });
                    } else {
                        layer.msg(res.msg || '数据加载失败');
                        tableData = [];
                    }
                }).catch(function (error) {
                    layer.close(loadingIndex);
                    layer.msg('网络请求失败');
                    console.error('Error:', error);
                    tableData = [];
                });
            }

            // 筛选函数
            function filterData(keyword = '') {
                if (!tableData.length) return;

                var filteredData;
                if (keyword.trim() === '') {
                    filteredData = tableData;
                } else {
                    filteredData = tableData.filter(item => {
                        var matchCode = item.design_code && item.design_code.toString().includes(keyword);
                        var matchName = item.project_name && item.project_name.toString().includes(keyword);
                        return matchCode || matchName;
                    });
                }

                table.reload('projectTable', {
                    data: filteredData,
                    page: false
                });
            }

            // 初始化
            function init() {
                initTable();
                loadData();

                // 输入法状态监听
                $('#search-input')
                    .on('compositionstart', function () {
                        isComposing = true;
                    })
                    .on('compositionend', function () {
                        isComposing = false;
                        var keyword = $(this).val();
                        filterData(keyword);
                    })
                    .on('input', function () {
                        if (!isComposing) {
                            var keyword = $(this).val();
                            filterData(keyword);
                        }
                    });

                // 搜索按钮点击事件
                $('#btn-search').on('click', function () {
                    var keyword = $('#search-input').val();
                    filterData(keyword);
                });

                // 回车键搜索
                $('#search-input').on('keydown', function (e) {
                    if (e.keyCode === 13) {
                        var keyword = $(this).val();
                        filterData(keyword);
                    }
                });

                // 双击行事件
                table.on('rowDouble(projectTable)', function (obj) {
                    var loadingIndex = layer.load(1);
                    http.get(API_CONFIG.ENDPOINTS.GET_PROJECT_RESUME, {
                        design_code: obj.data.design_code,
                        design_type: designType
                    }).then(function (res) {
                        layer.close(loadingIndex);
                        // 直接调用父页面函数
                        if (parent.handleProjectSelected) {
                            parent.handleProjectSelected(res.data);
                        }
                        // 关闭弹层
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    }).catch(function (error) {
                        layer.close(loadingIndex);
                        layer.msg('获取项目详情失败');
                        console.error('Error:', error);
                    });
                });
            }

            // URL参数获取
            function getUrlParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                return r ? decodeURIComponent(r[2]) : null;
            }

            // 启动初始化
            init();
        });
    </script>
</body>

</html>